package com.bjpowernode.web;

import com.bjpowernode.entity.TClue;
import com.bjpowernode.result.R;
import com.bjpowernode.service.TClueService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Slf4j
@RestController
@RequestMapping("/api/clue")
public class ClueController {

    @Resource
    private TClueService tClueService;

    @GetMapping("")
    public R clueByPage(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        log.info("current : {} ", current);
        PageInfo<TClue> tCluePageInfo = tClueService.getClueByPage(current);
        log.info("值 : " + tCluePageInfo.getPageSize());
        return R.OK(tCluePageInfo);
    }

    @PostMapping("importExcel")
    public R importExcel(MultipartFile file,
                         @RequestHeader(value = "Authorization") String jwt) throws IOException {
        log.info("要上传的数据文件信息file : {}" , file);
        // excel导入 , 即读文件 , 插入数据库
        System.out.println("file.getOriginalFilename() = " + file.getOriginalFilename());  // 全称包括后缀
        System.out.println("file.getName() = " + file.getName()); // 文件名
        System.out.println("file.getResource() = " + file.getResource());
        System.out.println("file.getSize() = " + file.getSize()); // 大小
        System.out.println("file.getContentType() = " + file.getContentType()); // 类型
        System.out.println("file.getInputStream() = " + file.getInputStream());
        tClueService.importExcel(file.getInputStream(), jwt);
        return R.OK();
    }

    @GetMapping("{id}")
    public R loadClueDetail(@PathVariable(value = "id")Integer id) {
        log.info("要查询的线索id : {}" , id);
        TClue tClue = tClueService.loadClueDetail(id);
        return R.OK(tClue);
    }


    @DeleteMapping("remove/{id}")
    public R removeById(@PathVariable(value = "id") Integer id) {
        log.info("要删除的id : {}" , id);
        int delete = tClueService.removeById(id);
        return delete >= 1 ? R.OK() : R.FAIL();
    }

    @DeleteMapping("batchRemove")
    public R batchRemove(@RequestParam(value = "ids") String ids) {
        log.info("要批量删除的id : {}" , ids);
        // 将数据转换回集合
        String[] idsStringArray = ids.split(",");
        List<Integer> idList = Arrays.stream(idsStringArray)
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        int delete = tClueService.batchRemove(idList);
        return delete >= 1 ? R.OK() : R.FAIL();
    }
}
